package com.ziyun.erp.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <p>discribe: excel 工具类 </p>
 * @author Zhao.gui
 * 2018年10月15日 下午9:24:35
 */
public class ExcelUtils {

	/**
	 *  文件导出
	 * @param fileName 文件名
	 * @param path 文件路径
	 * @param list 导出列表
	 */
	public static boolean exportExcel(String fileName,String path, Collection<?> list, Class<?> pojoClass) {
		Workbook workbook = null;
		OutputStream out = null;

		try {
			String pathName = path+"\\"+fileName+".xls";

			File file = FileUtils.creatFile(pathName);
			if(!file.exists()){
				file.mkdirs();
				file.createNewFile();
			}

			out = new FileOutputStream(file);
			workbook = ExcelExportUtil.exportExcel(new ExportParams(),pojoClass, list);
			workbook.write(out);
			out.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 以map形式导入 文件
	 * @param file
	 * @return
	 */
	public static List<Map<String, Object>> importExcelByMap(File file) {
		List<Map<String, Object>> list= ExcelImportUtil.importExcel(file , Map.class, new ImportParams());
		return list;
	}

	public static boolean exportExcelToWeb(ExportParams entity, Class<?> pojoClass,
                                           Collection<?> dataSet, HttpServletResponse response) {

		// 设置响应输出的头类型(设置响应类型)
		response.setHeader("content-Type", "application/json");
		// 下载文件的默认名称(设置下载文件的默认名称)
		response.setHeader("Content-Disposition", "attachment;filename=address.xls");
		//导出操作
		try {
			Workbook workbook = ExcelExportUtil.exportExcel(entity,pojoClass,dataSet);
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}
}
